package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;

import com.hjq.http.listener.HttpCallback;
import com.hjq.permissions.XXPermissions;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.entity.DeviceBaseConfigInfo;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.DeviceOtherBean;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.DeviceInfoParseUtil;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.DeviceTypeChangeEvent;
import com.qiantu.phone.ui.uiutil.DeviceMainType;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.setting.DeviceSettingAccess;
import com.qiantu.phone.widget.setting.DeviceGroupSettingDevice;
import com.qiantu.phone.widget.setting.DeviceSettingAngle;
import com.qiantu.phone.widget.setting.DeviceSettingAngleStroke;
import com.qiantu.phone.widget.setting.DeviceSettingArea;
import com.qiantu.phone.widget.setting.DeviceSettingBinding;
import com.qiantu.phone.widget.setting.DeviceSettingCalibration;
import com.qiantu.phone.widget.setting.DeviceSettingCardConfig;
import com.qiantu.phone.widget.setting.DeviceSettingChangeType;
import com.qiantu.phone.widget.setting.DeviceSettingCodeMatching;
import com.qiantu.phone.widget.setting.DeviceSettingCodeMotorReverse;
import com.qiantu.phone.widget.setting.DeviceSettingCommon;
import com.qiantu.phone.widget.setting.DeviceSettingCoor;
import com.qiantu.phone.widget.setting.DeviceSettingDimmingCycle;
import com.qiantu.phone.widget.setting.DeviceSettingFeedBack;
import com.qiantu.phone.widget.setting.DeviceSettingGroup;
import com.qiantu.phone.widget.setting.DeviceSettingIcon;
import com.qiantu.phone.widget.setting.DeviceSettingKeyChange;
import com.qiantu.phone.widget.setting.DeviceSettingKeyStudy;
import com.qiantu.phone.widget.setting.DeviceSettingLightShow;
import com.qiantu.phone.widget.setting.DeviceSettingLinkage;
import com.qiantu.phone.widget.setting.DeviceSettingModeSelection;
import com.qiantu.phone.widget.setting.DeviceSettingModifyKeyName;
import com.qiantu.phone.widget.setting.DeviceSettingName;
import com.qiantu.phone.widget.setting.DeviceSettingPanelLock;
import com.qiantu.phone.widget.setting.DeviceSettingScene;
import com.qiantu.phone.widget.setting.DeviceSettingSensitivity;
import com.qiantu.phone.widget.setting.DeviceSettingSensitivityRange;
import com.qiantu.phone.widget.setting.DeviceSettingShare;
import com.qiantu.phone.widget.setting.DeviceSettingShareSpace;
import com.qiantu.phone.widget.setting.DeviceSettingShowInMainView;
import com.qiantu.phone.widget.setting.DeviceSettingTODO;
import com.qiantu.phone.widget.setting.DeviceSettingTravel;
import com.qiantu.phone.widget.setting.DeviceSettingTriggerMode;
import com.qiantu.phone.widget.setting.DeviceSettingUnit;
import com.qiantu.phone.widget.setting.DeviceSettingUpgrade;
import com.qiantu.phone.widget.setting.DeviceSettingdoorPush;
import com.qiantu.phone.widget.setting.SettingAreaView;
import com.qiantu.phone.widget.setting.SettingDeleteBtn;
import com.qiantu.phone.widget.setting.SettingStopBtn;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class DeviceSettingActivity extends AppActivity {
    private Fragment deviceFragment;
    private FragmentManager mFragmentManager;
    private TranslateAnimation mShowTranslateAnimation;
    private TranslateAnimation mHideTranslateAnimation;
    private ViewGroup vContent;
    private DeviceSettingShowInMainView mDeviceSettingShowInMainView;

    private View deviceViewContainer;
    private String deviceSerialNo;
    private DeviceBean mDevice;
    private boolean needHideRightBtn = false;
    private DeviceOtherBean otherBean;
    private ControllerBean mController;
    @Log
    public static void start(Context context, String serialNo) {
        Intent intent = new Intent(context, DeviceSettingActivity.class);
        intent.putExtra("serialNo", serialNo);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Log
    public static void start(Context context, String serialNo, boolean needHideRightBtn) {
        Intent intent = new Intent(context, DeviceSettingActivity.class);
        intent.putExtra("serialNo", serialNo);
        intent.putExtra("needHideRightBtn", needHideRightBtn);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_setting;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        deviceSerialNo = getString("serialNo");
        needHideRightBtn = getBoolean("needHideRightBtn", false);
        vContent = findViewById(R.id.content);
        deviceViewContainer = findViewById(R.id.device_view_container);
        if(needHideRightBtn){
            getTitleBar().getRightView().setVisibility(View.GONE);
        }else{
            getTitleBar().getRightView().setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initData() {
        mDevice = LLDeviceDBManager.getInstance(getContext()).getDeviceBySerialNo(deviceSerialNo);
        if (mDevice!=null){
            if(mDevice.getHasControlCard() == 0 || mDevice.getIsDisable()){
                getTitleBar().getRightView().setVisibility(View.GONE);
                needHideRightBtn = true;
            }
            //        updateView();
            getSetting();
        }
    }

    public void getSetting(){
        if(mDevice.getDeviceGroup() == 0){
            LLHttpManager.getDeviceSettings(this, deviceSerialNo, new HttpCallback<HttpData<DeviceBean>>(this){
                @Override
                public void onStart(Call call) {
                    super.onStart(call);
                }

                @Override
                public void onSucceed(HttpData<DeviceBean> result) {
                    super.onSucceed(result);
                    DeviceBean newDevice = result.getData();
                    mDevice.setName(newDevice.getName());
                    mDevice.setImageUrl(newDevice.getImageUrl());
                    mDevice.setFloorName(newDevice.getFloorName());
                    mDevice.setFloorSerialNo(newDevice.getFloorSerialNo());
                    mDevice.setRoomName(newDevice.getRoomName());
                    mDevice.setRoomSerialNo(newDevice.getRoomSerialNo());
                    mDevice.setIsFavourite(newDevice.getIsFavourite());
                    mDevice.setStateData(newDevice.getStateData());
                    LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                    getOtherSetting();
                }

                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }

                @Override
                public void onEnd(Call call) {
                    super.onEnd(call);
                }
            });
        }else{
            getGroupOtherSetting();
            this.getTitleBar().getTitleView().setText(R.string.device_group_setting);
        }
    }

    public void getOtherSetting(){
        LLHttpManager.getDeviceInfo(this, deviceSerialNo, new HttpCallback<HttpData<DeviceOtherBean>>(this) {
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<DeviceOtherBean> result) {
                otherBean = result.getData();
                if(mDevice.getDeviceType().equals("dream_windowcurtains")){
                    getControllerData();
                }else{
                    updateView();
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    public void getGroupOtherSetting(){
        LLHttpManager.getGroupDeviceInfo(this, deviceSerialNo, new HttpCallback<HttpData<DeviceOtherBean>>(this) {
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<DeviceOtherBean> result) {
                otherBean = result.getData();
                if(mDevice.getDeviceType().equals("dream_windowcurtains")){
                    getControllerData();
                }else{
                    updateView();
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }

    public void getControllerData(){
        LLHttpManager.getControllerSettings(this, mDevice.getControllerSerialNo(), new HttpCallback<HttpData<ControllerBean>>(this){
            @Override
            public void onStart(Call call) {
                super.onStart(call);
            }

            @Override
            public void onSucceed(HttpData<ControllerBean> result) {
                super.onSucceed(result);
                mController = result.getData();
                updateView();
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }

            @Override
            public void onEnd(Call call) {
                super.onEnd(call);
            }
        });
    }


    private void updateView() {
        if (mDevice == null) {
            return;
        }
        DeviceBaseConfigInfo deviceBaseConfigInfo;
        if(mDevice.getDeviceGroup() == 0){
            deviceBaseConfigInfo = DeviceInfoParseUtil.parseData(this, mDevice.getDeviceType(), DeviceBaseConfigInfo.class);
        }else{
            deviceBaseConfigInfo = DeviceInfoParseUtil.parseData(this, "deviceGroup", DeviceBaseConfigInfo.class);
        }
        if(deviceBaseConfigInfo == null){
            return;
        }
        ControllerBean controllerBean = LLControllerDBManager.getInstance(getContext()).getControllerBySerialNo(mDevice.getControllerSerialNo());
        List<List<String>> settingData = deviceBaseConfigInfo.getSettingData();
        vContent.removeAllViews();
        for (List<String> list : settingData){
            SettingAreaView settingAreaView = new SettingAreaView(this);
            for (String item : list){
                if(!"0x0002".equals(mDevice.getProductModel())){
                    if("Device_Setting_DeviceGroup".equals(item)){
                         continue;
                    }
                }
                if(AppApplication.isHuawei() && "Device_Setting_FeedBack".equals(item)){
                    continue;
                }
                if("0x2506".equals(mDevice.getProductModel())){
                    if("Device_Setting_sensor_TypeChange".equals(item) && mDevice.getPos() == 1){
                        continue;
                    }
                    if("Device_Setting_Sensitivity_Range".equals(item) && mDevice.getPos() != 1){
                        continue;
                    }
                }else{
                    if("Device_Setting_Sensitivity_Range".equals(item)){
                        continue;
                    }
                }
                if(mDevice.getDeviceType().equals("dream_windowcurtains")){
                    if(mController.getProtocol().getBrandValue() == 3504){
                        if("Device_Angle_Setting".equals(item)){
                            continue;
                        }
                    }else{
                        if("Device_Setting_AngleStroke".equals(item)){
                            continue;
                        }
                        if("Device_Setting_MotorReverse".equals(item)){
                            continue;
                        }
                    }
                }
                View itemView = getItemView(item);
                settingAreaView.addView(itemView);
            }
            vContent.addView(settingAreaView);
        }
        SettingStopBtn btnStopStartUsing = new SettingStopBtn(this, mDevice);
        vContent.addView(btnStopStartUsing);
//        if(DeviceMainType.WALL_SWITCH.stringType.equals(mDevice.getType())){
//            SettingDeleteBtn deleteBtn = new SettingDeleteBtn(this, mDevice);
//            vContent.addView(deleteBtn);
//        }
        updateViewByIsDisable();
    }

    public void updateViewByIsDisable(){
        if (mDevice.getIsDisable()) {
            if (mDeviceSettingShowInMainView != null) {
                mDeviceSettingShowInMainView.setVisibility(View.GONE);
            }
        } else {
            if (mDeviceSettingShowInMainView != null) {
                mDeviceSettingShowInMainView.setVisibility(View.VISIBLE);
            }
        }
        //titlebar,右键显示才根据是否停用更新
        if(!needHideRightBtn) {
            getTitleBar().getRightView().setVisibility(mDevice.getIsDisable() ? View.GONE : View.VISIBLE);
        }
    }

    private View getItemView(String item) {
        if ("Device_Setting_Name".equals(item)){
            return new DeviceSettingName(this, mDevice);
        }else if ("Device_Setting_Icon".equals(item)){
            return new DeviceSettingIcon(this, mDevice);
        }else if ("Device_Setting_Area".equals(item)){
            return new DeviceSettingArea(this, mDevice);
        }else if ("Device_Setting_Common".equals(item)){
            return new DeviceSettingCommon(this, mDevice);
        }else if ("Device_Setting_ShowInMainView".equals(item)){
            //保存全局变量，停启用后更新是否隐藏
            mDeviceSettingShowInMainView = new DeviceSettingShowInMainView(this, mDevice);
            return mDeviceSettingShowInMainView;
        }else if ("Device_Setting_Coor".equals(item)){
            return new DeviceSettingCoor(this, mDevice);
        }else if ("Device_Setting_Binging".equals(item)){
            return new DeviceSettingBinding(this, mDevice);
        }else if ("Device_Setting_FeedBack".equals(item)){
            return new DeviceSettingFeedBack(this, mDevice);
        }else if ("Device_Setting_Share".equals(item)){
            return new DeviceSettingShare(this, mDevice, getString(R.string.device_share));
        }else if ("Device_Setting_KeyChange".equals(item)){
            return new DeviceSettingKeyChange(this, mDevice, getString(R.string.key_change));
        }else if ("Device_Setting_InfraredStudy".equals(item)){
            return new DeviceSettingKeyStudy(this, mDevice, getString(R.string.key_study));
        }else if ("Device_Setting_CodeMatching".equals(item)){
            return new DeviceSettingCodeMatching(this, mDevice, getString(R.string.code_matching));
        }else if ("Device_Setting_MotorReverse".equals(item)){
            return new DeviceSettingCodeMotorReverse(this, mDevice, getString(R.string.motor_reverse));
        }else if("Device_Setting_DimmingCycle".equals(item)){
            return new DeviceSettingDimmingCycle(this, mDevice, getString(R.string.dimming_cycle));
        }else if("Device_Setting_KeyName".equals(item)){
            return new DeviceSettingModifyKeyName(this, mDevice, otherBean.getRemainScanTimes(), getString(R.string.modify_key_name));
        }else if("Device_Setting_Update".equals(item)){
            return new DeviceSettingUpgrade(this, mDevice);
        }else if("Device_Setting_PanelLock".equals(item)){
            return new DeviceSettingPanelLock(this, mDevice);
        }else if("Device_Setting_Sensitivity".equals(item)){
            return new DeviceSettingSensitivity(this, mDevice, getString(R.string.sensitivity));
        }else if("Device_Setting_Triggered".equals(item)){
            return new DeviceSettingTriggerMode(this, mDevice);
        }else if("Device_Setting_LightShow".equals(item)){
            return new DeviceSettingLightShow(this, mDevice, getString(R.string.indicator_light_name));
        }else if("Device_Setting_DeviceGroup".equals(item)){
            return new DeviceSettingGroup(this, mDevice);
        }else if("DeviceGroup_Setting_Name".equals(item)){
            return new DeviceSettingName(this, mDevice);
        }else if ("DeviceGroup_Setting_Icon".equals(item)){
            return new DeviceSettingIcon(this, mDevice);
        }else if ("DeviceGroup_Setting_Devices".equals(item)){
            return new DeviceGroupSettingDevice(this, mDevice);
        }else if ("Device_Setting_sensor_TypeChange".equals(item)){
            return new DeviceSettingChangeType(this, mDevice);
        }else if ("Device_Setting_ModeSelection".equals(item)){
            return new DeviceSettingModeSelection(this, mDevice);
        }else if ("Device_Setting_DoorPushSettings".equals(item)){
            return new DeviceSettingdoorPush(this,mDevice,getString(R.string.doorbell_push));
        }else if ("Device_Setting_AccessControlEvent".equals(item)){
            return new DeviceSettingAccess(this,mDevice,getString(R.string.entrance_guard));
        }else if ("Device_Setting_Unit".equals(item)){
            return new DeviceSettingUnit(this, mDevice);
        }else if ("Device_Setting_Scene".equals(item)){
            return new DeviceSettingScene(this, mDevice,otherBean == null ? 0 : otherBean.getSceneCount());
        }else if ("Device_Setting_Linkage".equals(item)){
            return new DeviceSettingLinkage(this, mDevice,otherBean == null ? 0 :otherBean.getLinkageCount());
        }else if ("Device_Setting_Calibration".equals(item)){
            return new DeviceSettingCalibration(this, mDevice);
        }else if ("Device_Setting_Sensitivity_Range".equals(item)){
            return new DeviceSettingSensitivityRange(this, mDevice);
        }else if ("Device_Setting_DeviceCardConfig".equals(item)){
            return new DeviceSettingCardConfig(this, mDevice);
        }else if ("Device_Curtain_Stroke_Setting".equals(item)){
            return new DeviceSettingTravel(this, mDevice,getString(R.string.travel_setting));
        }else if ("Device_Angle_Setting".equals(item)){
            return new DeviceSettingAngle(this, mDevice,getString(R.string.angle_setting));
        }else if ("Device_Setting_ShareSpace".equals(item)){
            return new DeviceSettingShareSpace(this, mDevice,getString(R.string.share_space));
        }else if ("Device_Setting_AngleStroke".equals(item)){
            return new DeviceSettingAngleStroke(this, mDevice,"角度行程设置");
        }
        return new DeviceSettingTODO(this, mDevice, item);
     }

    @Override
    public void onRightClick(View view) {
        showDeviceView(LLDeviceUtil.getDeviceDetailPage(mDevice, 2));
    }

    public void showDeviceView(Fragment fragment) {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (deviceFragment != null && deviceFragment.isAdded()) {
            transaction.remove(deviceFragment);
        }
        deviceFragment = fragment;
        transaction.add(R.id.device_view_container, fragment, "device_view");
        // 事务提交
        transaction.commitNowAllowingStateLoss();
        deviceViewContainer.setVisibility(View.VISIBLE);
        ViewGroup contentView = deviceViewContainer.findViewById(R.id.content_view);
        if (contentView.getChildCount() > 0) {
            View deviceView = contentView.getChildAt(0);
            showTopBottomAnimation(deviceView);
//            showScaleAnimation(clickView, deviceView);
        }
    }

    public boolean hideDeviceView() {
        if (mFragmentManager == null) {
            mFragmentManager = getSupportFragmentManager();
        }
        deviceFragment = mFragmentManager.findFragmentByTag("device_view");
        if (deviceFragment != null) {
            ViewGroup contentView = deviceViewContainer.findViewById(R.id.content_view);
            if (contentView.getChildCount() > 0) {
                View deviceView = contentView.getChildAt(0);
                hideTopBottomAnimation(deviceView);
                return true;
            }
        }
        return false;
    }

    private void showTopBottomAnimation(View deviceView) {
        if (mShowTranslateAnimation == null) {
            mShowTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0);
            mShowTranslateAnimation.setDuration(300);//跑一个周期所用时长
            mShowTranslateAnimation.setInterpolator(new FastOutSlowInInterpolator());
        }
        deviceView.setVisibility(View.VISIBLE);
        deviceView.startAnimation(mShowTranslateAnimation);
    }

    private void hideTopBottomAnimation(View deviceView) {
        if (mHideTranslateAnimation == null) {
            mHideTranslateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);
            mHideTranslateAnimation.setDuration(300);//跑一个周期所用时长
            mHideTranslateAnimation.setInterpolator(new FastOutSlowInInterpolator());
            mHideTranslateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    FragmentTransaction transaction = mFragmentManager.beginTransaction();
                    if (deviceFragment != null && deviceFragment.isAdded()) {
                        transaction.remove(deviceFragment);
                    }
                    // 事务提交
                    transaction.commitNowAllowingStateLoss();
                    deviceViewContainer.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        deviceView.startAnimation(mHideTranslateAnimation);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeviceTypeChangeEvent(DeviceTypeChangeEvent event) {
        mDevice = LLDeviceDBManager.getInstance(AppApplication.getInstance()).getDeviceBySerialNo(mDevice.getDeviceSerialNo());
       updateView();
    }

    @Override
    public void onBackPressed() {
        if (hideDeviceView()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}